#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <string>

using namespace std;

void Usage(string proc)
{
    cout << "\n\tUsage: " << proc << " serverip serverport\n"
         << endl;
}

// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    server.sin_port = htons(serverport);

    while (true)
    {
        int cnt = 5;
        int isreconnect = false; // 是否需要重连
        int sockfd = 0;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            cerr << "socket create failed" << endl;
            return 1;
        }

        do  // 重连 模块
        {
            // tcp 客户端要不要 bind？  不需要显式的 绑定 ip、端口号，，操作系统 随机选择
            // 什么时候绑定?   客户端发起 connect 的时候,自动随机 绑定端口
            int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isreconnect = true;
                cerr << "connect failed...... , reconnect: " << cnt << endl;
                cnt--;
                sleep(1);
            }
            else
            {
                // isreconnect = false;
                break;
            }

        } while (cnt && isreconnect);

        if (cnt == 0)
        {
            cerr << "user offline..." << endl;
            break;
        }

        string message;

        cout << "Please Enter# ";
        getline(cin, message);

        int n2 = write(sockfd, message.c_str(), message.size());
        if (n2 < 0)
        {
            // isreconnect = true; // 需要进行重连
            cerr << "write error......" << endl;
            continue;
        }

        char inbuffer[4096];
        int n3 = read(sockfd, inbuffer, sizeof(inbuffer));
        if (n3 > 0)
        {
            inbuffer[n3] = 0;
            cout << inbuffer << endl;
        }
        close(sockfd);
    }

    return 0;
}